#!/bin/bash
echo "***********************************"
echo "*                                 *"
echo "*   Freebox record downloader     *"
echo "*                                 *"
echo "***********************************"

INPUT_DIR=.
FINAL_DIR=..
CREDENTIAL=`cat .credential`
LAST_MIRROR_FILE="$INPUT_DIR/.last_mirror"


# do not allow concurrency 
if [ -e "$INPUT_DIR/.lock" ]; then
  exit 1
else
  touch "$INPUT_DIR/.lock"
fi


function cleanup_action {
  rm -f "$INPUT_DIR/.listing1.txt"
  rm -f "$INPUT_DIR/.listing2.txt"
  rm -f "$INPUT_DIR/.lock"
}

function clean_shutdown {
  echo "shutdown sequence..."  
  cleanup_action
  exit 1
}

trap 'clean_shutdown' SIGTERM SIGINT SIGHUP

# do not start download if the freebox is recording
lftp -u $CREDENTIAL -e "open; ls /Disque\ dur/Enregistrements/ ; quit" hd1.freebox.fr > "$INPUT_DIR/.listing1.txt"
sleep 5
lftp -u $CREDENTIAL -e "open; ls /Disque\ dur/Enregistrements/ ; quit" hd1.freebox.fr > "$INPUT_DIR/.listing2.txt"
cmp -s "$INPUT_DIR/.listing1.txt" "$INPUT_DIR/.listing2.txt" > /dev/null
if [ $? -eq 0 ]; then
  if [ -e "$LAST_MIRROR_FILE" ]; then  
    LAST_MIRROR=`cat "$LAST_MIRROR_FILE"`
  else
    LAST_MIRROR=0
  fi
  LAST_MIRROR_DATE=`date +%Y%m%d`
  lftp -u $CREDENTIAL -e "mirror -c --newer-than=$LAST_MIRROR /Disque\ dur/Enregistrements/ .; quit" hd1.freebox.fr 
  # mirroring finished, save the current date because
  # we don't want to download these files again
  echo $LAST_MIRROR_DATE > "$LAST_MIRROR_FILE"
  # move files to processing dir if not buzy
  if [ ! -e "$FINAL_DIR/.lock" ]; then
    mv -u -f *.ts "$FINAL_DIR"
    if [ $? -eq 0 ]; then
      ./clean_fbx.py
    fi
  fi
fi



cleanup_action
